package com.taoye.thread;

public class Demo21 {
	public static void main(String[] args) throws InterruptedException {
		Demo21Service service = new Demo21Service();
		Thread t = new Demo21Thread(service);
		t.setName("A");
		t.start();
		Thread t2 = new Demo21Thread(service);
		t2.setName("B");
		t2.start();
	}
}

class Demo21Service {
	//根据19的例子，将number设置为成员变量
	private int number = 10;
	
	synchronized public void setNumber(String name) {
		if(name.equals("A")) {
			//线程A先进来设置了以后 线程B立马修改number变量的值测试是否造成脏读
			number = 100;
			System.out.println("线程A设置完成了,当前值为："+number);
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}else {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			number = 200;
			System.out.println("线程B设置完成了,当前值为："+number);
		}
		System.out.println("线程"+name+"的值为：" + number);
	}
}

class Demo21Thread extends Thread {
	private Demo21Service service;
	
	public Demo21Thread(Demo21Service service) {
		this.service = service;
	}
	@Override
	public void run() {
		service.setNumber(getName());
	}
}
